function CustomPromise(exec) {

    this.onResolveCallbacks = [];

    this.onRejectCallbacks = [];

    this.status = 'pending';

    this.value;

    this.reason;
    
    try {
        exec(resolve, reject);
    }
    catch (error) {
        reject(error);
    }

    var self = this;

    function resolve(v) {
        if (self.status === 'pending') {
            self.status = 'resolve';
            self.value = v;
            self.onResolveCallbacks.forEach(item => item())
        }
    }

    function reject(r) {
        if (self.status === 'pending') {
            self.status = 'reject';
            self.reason = r;
            self.onRejectCallbacks.forEach(item => item())
        }
    }
}

function resolvePromise(promise, res, resolve, reject) {
    if (promise === res) {
        throw new TypeError('循环调用');
    }

    if (res instanceof CustomPromise) {
        res.then.call(res, (res) => {
            resolvePromise(promise, res, resolve, reject);
        }, (reason) => {
            reject(reason);
        })
    }
    else {
        resolve(res);
    }
}

CustomPromise.prototype.then = function (onResolve, onReject) {
    onResolve = typeof onResolve === 'function' ? onResolve : (v) => v
    onReject = typeof onReject === 'function' ? onReject : (r) => r
    
    var self = this;

    const promise = new CustomPromise((resolve, reject) => {
        // 如果当前异步操作还未完成，将onResolve加入回调队列
        if (self.status === 'pending') {
            self.onResolveCallbacks.push(() => {
                try {
                    let res = onResolve(self.value);
                    // 如果res是promise对象，则需要继续执行then方法
                    resolvePromise(promise, res, resolve, reject)
                }
                catch (error) {
                    reject(error);
                }
            })
        }
        // 如果当前异步曹组已完成， 执行onResolve
        else if (self.status === 'resolve') {
            try {
                let res = onResolve(self.value);
                // 如果res是promise对象，则需要继续执行then方法
                resolvePromise(promise, res, resolve, reject)
            }
            catch (error) {
                reject(error);
            }
        }
        // 如果当前异步操作失败, 执行 onReject
        else if (self.status === 'reject') {
            try {
                let res = onReject(self.reason);
                // 如果res是promise对象，则需要继续执行then方法
                resolvePromise(promise, res, resolve, reject)
            }
            catch (error) {
                reject(error);
            }
        }
    });

    return promise;
}

const p = new CustomPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(123);
    }, 1000);
});

p.then((value) => {
    console.log(value, '+++++++++++++++++++')
    return new CustomPromise((resolve) => {
        setTimeout(() => {
            resolve();
        }, 1000)
    }).then(() => {
        console.log('第二个promise');
        return '第二个Promise的结果'
    })
}).then(res => {
    console.log(res)
})